package com.zhugang.week04;

/**
 * @program algorithms
 * @description: sortArrayByParity
 * @author: chanzhugang
 * @create: 2022/06/17 16:45
 */
public class SortArrayByParity {

    public static void main(String[] args) {
        SortArrayByParity sortArrayByParity = new SortArrayByParity();
        int[] a = new int[]{1, 4, 2, 3};
        int[] res = sortArrayByParity.sortArrayByParity(a);
        for (int i : res) {
            System.out.println(i);
        }
    }

    /**
     * 特殊排序：奇数位于数组前半部分，偶数位于数组后半部分
     *
     * @param a
     * @return
     */
    public int[] sortArrayByParity(int[] a) {
        /**
         * [1,4,2,3]  -> [1,3,2,4]
         * 双指针i、j
         * i是奇数，i++、j是偶数，j--; 否则交换
         */
        int i = 0;
        int j = a.length - 1;
        while (i < j) {
            if (a[i] % 2 == 1) {
                i++;
                continue;
            }
            if (a[j] % 2 == 0) {
                j--;
                continue;
            }
            // a[i]是偶数，a[j]是奇数，交换
            int temp = a[i];
            a[i] = a[j];
            a[j] = temp;
            i++;
            j--;
        }
        return a;
    }
}